package com.example.consumptionrecords.config.shiro;

import com.example.consumptionrecords.entity.enums.GlobalConstants;
import com.example.consumptionrecords.entity.pojo.User;
import com.example.consumptionrecords.exception.UserException;
import com.example.consumptionrecords.mapper.UserMapper;
import com.example.consumptionrecords.util.redis.RedisUtil;
import jakarta.annotation.Resource;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * 自定义Realm（手机验证码登录）
 * hhzr9
 * 2024 \ 03 \ 31
 */

public class PhoneRealm extends AuthorizingRealm {

	@Resource
	private UserMapper userMapper;

	@Resource
	private RedisUtil redisUtil;

	public PhoneRealm() {
		// 设置支持的Token
		setAuthenticationTokenClass(PhoneAuthCodeToken.class);
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
		// 判断当前的登录方式
		if (authenticationToken instanceof PhoneAuthCodeToken) {
			// 获取手机号
			String phone = (String) authenticationToken.getPrincipal();
			// 从数据库中获取用户信息
			User user = userMapper.selectUserByUsernameOrPhone(phone);
			if (user == null) {
				throw new UnknownAccountException(GlobalConstants.USER_NOT_EXIST.getMessage());
			}
			if (!redisUtil.exists(phone)) {
				// 验证码过期
				throw new UserException(GlobalConstants.USER_AUTH_CODE_TIMEOUT_ERR.getCode(), GlobalConstants.USER_AUTH_CODE_TIMEOUT_ERR.getMessage());
			}
			// 判断验证码是否正确
			String cacheAuthCode = (String)redisUtil.get(phone);
			return new SimpleAuthenticationInfo(user, cacheAuthCode, getName());
		}
		return null;
	}

	@Override
	public boolean supports(AuthenticationToken token) {
		return token instanceof PhoneAuthCodeToken;
	}
}
